﻿using System;
using System.IO;
using invrt;
using Pibby.Core.IO;

namespace Pibby.Core
{
	public static class ApplicationSettingsFinder
	{
        public static PerUserSettings LoadSettings(string fileName, IFolderCollection searchPaths, IFolder defaultSettings, IFolder defaultDownload)
		{
            var settings = new PerUserSettings();
			var streamFactory = InversionOfController.Factory.CreateTypeOf<ITextWriterFactory>();

            IFile settingsFile = null;

            try
            {
                // first try to find the settings we will use to find everything else...
                var readFactory = InversionOfController.Factory.CreateTypeOf<ITextReaderFactory>();
                settingsFile = FileSearcher.Find(fileName, searchPaths);

                using (var reader = readFactory.FromFile(settingsFile.Path))
                {
                    settings = new PerUserSettings(PerUserSettings.Load(reader));
                    settings.Path = settingsFile.Path;
                }
            }
            catch (FileNotFoundException)
			{
                settings = CreateNewSettingsFile(fileName, defaultSettings);
			}
            catch (Exception)
            {
                // if there's a problem with the settings file - kill it and start again...
                if (settingsFile != null && settingsFile.Exists)
                {
                    settingsFile.Delete();
                    settings = CreateNewSettingsFile(fileName, defaultSettings);
                }
            }

			if (string.IsNullOrEmpty(settings.DownloadFolder))
			{
				settings.DownloadFolder = defaultDownload.Path;
			}

			var folderFactory = InversionOfController.Factory.CreateTypeOf<IFolderFactory>();

			var folder = folderFactory.GetFolder(settings.DownloadFolder);
			folder.AutoCreate = true;

            settings.Save();

            return settings;
		}

        private static PerUserSettings CreateNewSettingsFile(string fileName, IFolder defaultSettings)
        {
            var settings = new PerUserSettings();

            // create a new file in the default location...
            settings.Path = defaultSettings.PathToFile(fileName);
            settings.Save();

            return settings;
        }
	}
}
